<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文介绍，如何在FreeRTOS中创建一个任务，并设置合理的任务栈大小。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS——创建任务">
<meta property="og:url" content="http://fengxun2017.github.io/2022/10/29/FreeRTOS-%E5%88%9B%E5%BB%BA%E4%BB%BB%E5%8A%A1/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="本文介绍，如何在FreeRTOS中创建一个任务，并设置合理的任务栈大小。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-10-28T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-02T13:59:17.090Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://fengxun2017.github.io/2022/10/29/FreeRTOS-%E5%88%9B%E5%BB%BA%E4%BB%BB%E5%8A%A1/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2022/10/29/FreeRTOS-%E5%88%9B%E5%BB%BA%E4%BB%BB%E5%8A%A1/","path":"2022/10/29/FreeRTOS-创建任务/","title":"FreeRTOS——创建任务"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS——创建任务 | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#FreeRTOS%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BA%E4%BB%BB%E5%8A%A1%EF%BC%9A"><span class="nav-number">1.</span> <span class="nav-text">FreeRTOS如何创建任务：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#FreeRTOS-%E5%A6%82%E4%BD%95%E7%A1%AE%E5%AE%9A%E4%BB%BB%E5%8A%A1%E6%A0%88%E7%9A%84%E5%A4%A7%E5%B0%8F%EF%BC%9A"><span class="nav-number">2.</span> <span class="nav-text">FreeRTOS 如何确定任务栈的大小：</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2022/10/29/FreeRTOS-%E5%88%9B%E5%BB%BA%E4%BB%BB%E5%8A%A1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS——创建任务 | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS——创建任务
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-10-29 00:00:00" itemprop="dateCreated datePublished" datetime="2022-10-29T00:00:00+08:00">2022-10-29</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.6k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>6 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>

<p>本文介绍，如何在FreeRTOS中创建一个任务，并设置合理的任务栈大小。</p>
</center>

<span id="more"></span>

<hr>
<p>如何基于自己的开发板新建FreeRTOS工程可以参考：<a href="https://fengxun2017.github.io/2022/10/25/%E5%9F%BA%E4%BA%8Ecrotex-m%E5%A4%84%E7%90%86%E5%99%A8%E6%96%B0%E5%BB%BAFreeRTOS%E5%B7%A5%E7%A8%8B/">基于crotex-m处理器新建FreeRTOS工程</a></p>
<h4 id="FreeRTOS如何创建任务："><a href="#FreeRTOS如何创建任务：" class="headerlink" title="FreeRTOS如何创建任务："></a>FreeRTOS如何创建任务：</h4><p>在多任务操作系统中，每个任务都可以看做是一个独立的”小应用”，操作系统负责对各个任务进行调度。FreeRTOS对任务的函数原型定义如下：</p>
<p><code>void ATaskFunction( void *pvParameters );</code></p>
<p>即每个任务的入口函数必须为上面的形式(无RTOS的裸机程序，可以认为入口函数就是Main函数)。一般任务的入口函数实现形式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">ATaskFunction</span><span class="params">( <span class="type">void</span> *pvParameters )</span></span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; )</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">// 这里实现任务功能代码</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 任务退出前需要删除自己</span></span><br><span class="line">    vTaskDelete( <span class="literal">NULL</span> );</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>嵌入式设备通常都是实现某个单一应用功能，当设备上电后，其程序就一直保持运行，直到设备断电。所以裸机开发时，都是main函数中实现一个无线循环，让其不停运行。</p>
<p>而到了RTOS上，应用的整体功能被拆分成多个任务，可以认为每个任务都是作为整体功能一部分的“小应用”。所以,一般情况下，这些任务也是一直运行的。因此，其实现也是内部一个无限的循环(如上述代码所示)。当然，也有一些情况下，某些任务不需要在运行了，这种情况下，我们可以让它跳出这个大循环，然后删除自己(上述代码，<code>NULL传入vTaskDelete</code>即表示删除调用这个函数的任务本身)。<br>ps：严格来说，是将自己放入等待结束队列中，RTOS自带的idle任务会负责实际的删除。因为任务无法删除自己，删除自己意味着要释放任务所占的任务控制块结构体信息，以及这个任务所拥有的栈，而任务执行代码又依赖于这些资源。</p>
<p>实现了任务函数后，还需要将其创建出来，即实例化出一个具体的任务。FreeRTOS提供了如下任务创建接口(该接口会动态申请任务需要的内核结构和任务需要的栈空间，不需要外部提供)：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xTaskCreate</span><span class="params">( TaskFunction_t pvTaskCode, </span></span><br><span class="line"><span class="params">                        <span class="type">const</span> <span class="type">char</span> * <span class="type">const</span> pcName, </span></span><br><span class="line"><span class="params">                        <span class="type">uint16_t</span> usStackDepth, </span></span><br><span class="line"><span class="params">                        <span class="type">void</span> *pvParameters, </span></span><br><span class="line"><span class="params">                        UBaseType_t uxPriority, </span></span><br><span class="line"><span class="params">                        TaskHandle_t *pxCreatedTask )</span>;</span><br></pre></td></tr></table></figure>
<p> 其中：</p>
<ul>
<li><code>pvTaskCode：</code>即任务函数</li>
<li><code>pcName：</code>可以给该任务命名，该名字是用来调试用的，FreeRTOS提供了一些辅助函数，可以获取系统中当前运行的任务的状态信息，通过这个名字可以更清楚的知道每个任务的具体作用。</li>
<li><code>usStackDepth：</code>为任务栈大小(如果任务函数中没有很深的函数嵌套调用，任务函数内部也没有定义大的临时数组，则一般设置个200左右的值即可)。</li>
<li><code>pvParameters：</code> 在任务的入口函数定义中也有一个参数<code>void ATaskFunction( void *pvParameters )</code>，任务创建时填入的该参数，在任务实际运行时就会传递给任务。</li>
<li><code>uxPriority：</code>任务优先级，值越大，优先级越高。FreeRTOS会优先让优先级更高的任务运行（该值需要小于FreeRTOSConfig.h中配置的<code>configMAX_PRIORITIES</code>）。</li>
<li><code>pxCreatedTask： </code>任务句柄，FreeRTOS会将该值设置为当前任务的句柄（即在系统内唯一标识一个任务），例如你的应用中存在任务A在某个条件下会删除任务B。那么，任务A就需要保存任务B的句柄，并且调用<code>vTaskDelete( TaskHandle_t pxTask )</code>时传入任务B的句柄，即可删除任务B。</li>
<li><strong>返回值</strong>：创建成功时返回pdPASS，其它值表示失败(例如，堆空间所剩的ram资源已经不足够创建任务的内核数据结构和栈空间了)。</li>
</ul>
<p>任务创建成功后，就是启动FreeRTOS的内核，让其开始进行任务的调度。<br>即调用：<code>vTaskStartScheduler()</code></p>
<p>如下是一个启动两个任务的demo，分别闪烁两个LED灯，两个任务都是使用的同一个入口函数，通过传递不同的LED参数使它们闪烁不同的LED。(虽然使用的是同一个入口函数，但是任务创建后它们是作为两个独立任务存在的)</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">include <span class="string">&quot;FreeRTOS.h&quot;</span></span><br><span class="line">include <span class="string">&quot;task.h&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">led_flash</span><span class="params">( <span class="type">void</span> * pvParameters )</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">const</span> <span class="type">uint32_t</span> LED_NUM = *(<span class="type">uint32_t</span> *)pvParameters;</span><br><span class="line">    <span class="type">const</span> TickType_t xDelay = <span class="number">500</span> / portTICK_PERIOD_MS;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>) &#123;</span><br><span class="line">        vTaskDelay( xDelay );</span><br><span class="line">        nrf_gpio_pin_toggle(LED_NUM);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">uint32_t</span> LED_1 = <span class="number">13</span>, LED_2 = <span class="number">14</span>;</span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> </span><br><span class="line">&#123;</span><br><span class="line">    TaskHandle_t task_handle1=<span class="literal">NULL</span>, task_handle2=<span class="literal">NULL</span>;</span><br><span class="line"></span><br><span class="line">    bsp_board_leds_init();</span><br><span class="line"></span><br><span class="line">    xTaskCreate(led_flash,       </span><br><span class="line">                <span class="string">&quot;NAME&quot;</span>,         </span><br><span class="line">                <span class="number">200</span>,    <span class="comment">/* stack size */</span></span><br><span class="line">                &amp;LED_1,    </span><br><span class="line">                <span class="number">2</span>,</span><br><span class="line">                &amp;task_handle1);      </span><br><span class="line"></span><br><span class="line">    xTaskCreate(led_flash,      </span><br><span class="line">                <span class="string">&quot;NAME&quot;</span>,         </span><br><span class="line">                <span class="number">200</span>,     </span><br><span class="line">                &amp;LED_2,   </span><br><span class="line">                <span class="number">2</span>,</span><br><span class="line">                &amp;task_handle2);   </span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/* Start the created tasks running. */</span></span><br><span class="line">    vTaskStartScheduler();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/* Execution will only reach here if there was insufficient heap to</span></span><br><span class="line"><span class="comment">    start the scheduler. */</span></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意</strong>：上述LED标记变量<code>uint32_t LED_1 = 13, LED_2 = 14; </code>是定义成全局的，不能在main函数内部定义。因为，在调用<code>vTaskStartScheduler()</code>启动内核调度后，内核会重置main函数的栈以作它用。所以Main函数栈中的变量会变得无效。(FreeRTOS在启动内核调度后，<strong>就永远不会再返回main函数中了</strong>，只会调度创建的任务，所以FreeRTOS可以重置main的栈用来做其它用途)<br><strong>注意</strong>：由于FreeRTOS在调用<code>vTaskStartScheduler</code>启动后就不会再返回到main函数中，所以也不要在Main函数中编写业务代码。main函数中基本只做一些必要的初始化工作，以及创建所有任务。</p>
<h4 id="FreeRTOS-如何确定任务栈的大小："><a href="#FreeRTOS-如何确定任务栈的大小：" class="headerlink" title="FreeRTOS 如何确定任务栈的大小："></a>FreeRTOS 如何确定任务栈的大小：</h4><p>初期经验不足时，可能不清楚创建任务时应该设置多大的任务栈比较合适（<code>xTaskCreate</code>的参数<code>usStackDepth</code>）。在调试阶段，我们可先设置一个比较大的值，例如如果你的任务函数内没有局部数组变量，也没有很深的函数嵌套函数调用，可以直接设置一个200。如果，你的任务函数中有大的局部数组（例如<code>char buffer[N]</code>），你可以设置栈大小为 N+200（当前前提是你的mcu中的确有那么多ram空间，没有的话就改小，先试试）。<br>之后，再利用FreeRTOS内核提供的 <code>UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask )</code> 函数来获取函数运行过程中，栈的使用量。<br><strong>注意</strong>，使用该函数需要在头文件<code>FreeRTOSConfig.h</code>中增加配置<code>#define INCLUDE_uxTaskGetStackHighWaterMark 1</code></p>
<p>任务栈使用量的检测原理简单解释如下：<br>例如，任务A创建时设置的栈大小为200，则内核会为任务A申请了一个 200 字大小的内存空间作为栈（32位处理器中<strong>一个字是4字节</strong>，所以实际申请的是<strong>200*4字节</strong>空间）。在初始化任务信息时，内核会将该段RAM空间设置为一个<strong>特殊值(0xA5)</strong>,假设该段内存起始地址为0，结束地址为799，栈增长时地址会增加（这里是为了解释方便，实际上cortex-m3&#x2F;m4硬件都是”满减栈”，跟这里的描述是相反的）<br>初始时，栈内存状态如下，0-799地址空间都是0xA5：</p>
<table>
<thead>
<tr>
<th align="center">0</th>
<th align="center">1</th>
<th align="center">2</th>
<th align="center">3</th>
<th align="center">4</th>
<th align="center">…</th>
<th align="center">791</th>
<th align="center">792</th>
<th align="center">793</th>
<th align="center">794</th>
<th align="center">795</th>
<th align="center">796</th>
<th align="center">797</th>
<th align="center">798</th>
<th align="center">799</th>
</tr>
</thead>
<tbody><tr>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">…</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
</tr>
</tbody></table>
<p>程序运行一段时间后，最大时曾经使用到过791地址处，则内存状态如下(x表示其它值)：</p>
<table>
<thead>
<tr>
<th align="center">0</th>
<th align="center">1</th>
<th align="center">2</th>
<th align="center">3</th>
<th align="center">4</th>
<th align="center">…</th>
<th align="center">791</th>
<th align="center">792</th>
<th align="center">793</th>
<th align="center">794</th>
<th align="center">795</th>
<th align="center">796</th>
<th align="center">797</th>
<th align="center">798</th>
<th align="center">799</th>
</tr>
</thead>
<tbody><tr>
<td align="center">x</td>
<td align="center">x</td>
<td align="center">x</td>
<td align="center">x</td>
<td align="center">x</td>
<td align="center">…</td>
<td align="center">x</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
<td align="center">0xA5</td>
</tr>
</tbody></table>
<p>FreeRTOS提供的函数<code>uxTaskGetStackHighWaterMark</code>就是从799地址处往前检查，看还有多少值保持为0x5A，这里例子为8，则会返回2（返回的是字个数）这样曾经使用过的最大深度就是(200-2)，根据该值就可以将创建任务时的栈大小设置为一个更合适的值。</p>
<p>一个使用demo如下，<code>SEGGER_RTT_printf</code>替换成自己的调试输出函数：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">test_task</span><span class="params">( <span class="type">void</span> * pvParameters )</span></span><br><span class="line">&#123;</span><br><span class="line">    UBaseType_t uxHighWaterMark;</span><br><span class="line">    <span class="type">const</span> TickType_t xDelay = <span class="number">1000</span> / portTICK_PERIOD_MS;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>) &#123;</span><br><span class="line">        vTaskDelay( xDelay );</span><br><span class="line">        uxHighWaterMark = uxTaskGetStackHighWaterMark( <span class="literal">NULL</span> );</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;The maximum stack size ever used:%d\r\n&quot;</span>, <span class="number">200</span>-uxHighWaterMark);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line"></span><br><span class="line">    xTaskCreate(test_task,       </span><br><span class="line">                <span class="string">&quot;NAME&quot;</span>,         </span><br><span class="line">                <span class="number">200</span>,      </span><br><span class="line">                <span class="literal">NULL</span>,    </span><br><span class="line">                <span class="number">2</span>,</span><br><span class="line">                <span class="literal">NULL</span>);      </span><br><span class="line">    </span><br><span class="line">    vTaskStartScheduler();</span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我的调试信息显示如下，所以设置200大小的栈是完全没必要的：<br><code>The maximum stack size ever used:62</code></p>
<p><strong>最后：</strong> <code>uxTaskGetStackHighWaterMark</code>函数应该在开发阶段使用，正式发布的产品还是不要再使用了，毕竟每次调用都会遍历内存检查值。</p>
<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱

<br>
<br>
FreeRTOS交流QQ群-663806972

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2022/10/29/FreeRTOS-%E5%88%9B%E5%BB%BA%E4%BB%BB%E5%8A%A1/" title="FreeRTOS——创建任务">http://fengxun2017.github.io/2022/10/29/FreeRTOS-创建任务/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2022/10/27/why-use-RTOS/" rel="prev" title="为什么使用嵌入式实时操作系统(RTOS)">
                  <i class="fa fa-chevron-left"></i> 为什么使用嵌入式实时操作系统(RTOS)
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/11/01/FreeRTOS-task-status-management/" rel="next" title="FreeRTOS的任务调度和管理">
                  FreeRTOS的任务调度和管理 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
